<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="query.type" placeholder="请选择抬头类型" clearable>
        <el-option v-for="item in status" :key="item.key" :label="item.displayName" :value="item.key" />
      </el-select>
      <el-input v-model.trim="query.code" clearable placeholder="请输入快捷编号" @keyup.enter.native="search" />
      <el-button type="primary" icon="el-icon-search" @click="search">
        {{ $t('table.search') }}
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
        新增
      </el-button>
      <el-table :data="userList" highlight-current-row border :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="type" label="抬头类型">
          <template slot-scope="{row:{type}}">
            {{ type == 0 ? '我方抬头' : type == 1 ? '客户抬头' : '供应商抬头' }}
          </template>
        </el-table-column>
        <el-table-column prop="partnerName" label="客户/供应商" />
        <el-table-column prop="code" label="快捷编号" />
        <el-table-column prop="name" label="个人/公司名称" />
        <el-table-column prop="taxpayer" label="纳税人识别号" />
        <el-table-column prop="addressPhone" label="地址_电话" />
        <el-table-column prop="bankDetail" label="银行账号及开户行" />
        <!-- <el-table-column label="创建时间">
          <template slot-scope="{row}">
            <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间">
          <template slot-scope="{row}">
            <span v-if="!row.updateTime">{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            <span v-else>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column :label="$t('table.actions')" align="center">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleClick(1, row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button type="danger" size="mini" @click="handleClick(0, row)">
              {{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
        @pagination="getUserPage" />
      <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :title="user.id ? '编辑' : '新建'"
        @closed="dialogClose">
        <el-form :model="user" :rules="rules" ref="ruleForm" label-width="140px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="抬头类型" prop="type">
                <el-select style="width:100%" v-model="user.type" placeholder="请选择抬头类型" clearable
                  @change="handleChange">
                  <el-option v-for="item in status" :key="item.key" :label="item.displayName" :value="item.key" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="快捷编号" prop="code">
                <el-input v-model.trim="user.code" placeholder="请输入快捷编号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="个人/公司名称" prop="name">
                <el-input v-model.trim="user.name" placeholder="请输入个人/公司名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纳税人识别号" prop="taxpayer">
                <el-input v-model.trim="user.taxpayer" placeholder="请输入纳税人识别号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="地址_电话" prop="addressPhone">
                <el-input v-model.trim="user.addressPhone" placeholder="请输入地址_电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号及开户行" prop="bankDetail">
                <el-input v-model.trim="user.bankDetail" placeholder="请输入银行账号及开户行" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="user.type" :label="user.type == 1 ? '客户' : '供应商'" prop="partnersId">
                <el-select style="width: 100%;" v-model="user.partnersId"
                  :placeholder="`请选择${user.type == 1 ? '客户' : '供应商'}`" clearable>
                  <el-option v-for="item in partnersList" :key="item.id" :label="item.partnerName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" @click="dialogVisible = false">
            {{ $t('permission.cancel') }}
          </el-button>
          <el-button type="primary" @click="submit">
            {{ $t('permission.confirm') }}
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { sysInvoiceHeaderQuery, sysInvoiceHeaderUpdate, sysInvoiceHeaderAdd, sysInvoiceHeaderDelete, codePartnersGetAll } from '@/api/invoice'
import { deepClone, refreshArr, arraryRemove } from '../../../utils'
const defaultUser = {

}

const status = [
  { key: 0, displayName: '我方抬头' },
  { key: 1, displayName: '客户抬头' },
  { key: 2, displayName: '供应商抬头' }
]
export default {
  name: 'Users',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      rules: {
        type: [
          { required: true, message: '请选择抬头类型', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入快捷编号', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入个人/公司名称', trigger: 'blur' },
        ],
        taxpayer: [
          { required: true, message: '请输入纳税人识别号', trigger: 'blur' },
        ],
        addressPhone: [
          { required: true, message: '请输入地址_电话', trigger: 'blur' },
        ],
        bankDetail: [
          { required: true, message: '请输入银行账号及开户行', trigger: 'blur' },
        ],
        partnersId: [
          { required: true, validator: this.validatePass, trigger: 'blur' },

        ]
      },
      dialogVisible: false,
      user: Object.assign({}, defaultUser),
      total: 0,
      status: Object.freeze(status),
      query: {
        pageIndex: 1,
        pageSize: 10
      },
      currentPage: 1,
      pagesize: 10,
      userList: [],
      groups: [],
      roles: [],
      partnersList: []
    }
  },
  mounted() {
    this.getUserPage()
  },
  methods: {
    validatePass(rule, value, callback) {
      if (!value) {
        return callback(new Error(`请选择${this.user.type == 1 ? '客户' : '供应商'}`));
      } else {
        callback();
      }
    },
    async handleChange(e) {
      this.$set(this.user,'partnersId','')
      if (e) {
        this.partnersList = await codePartnersGetAll({
          type: e
        })
      }
    },
    async handleClick(val, item) {
      // 0-删除；1-编辑；
      const id = item.id
      switch (val) {
        case 0:
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            await sysInvoiceHeaderDelete({ id })
            this.$message.success('删除成功')
            this.getUserPage()
          })
          break;
        case 1:
          if(item.type != 0){
            this.handleChange(item.type)
          }
          this.user = deepClone(item)
          this.dialogVisible = true
          break;
      }
    },
    dialogClose() {
      this.$refs['ruleForm'].resetFields()
    },
    async getUserPage() {
      const { list, total } = await sysInvoiceHeaderQuery(this.query)
      this.userList = list
      this.total = total
    },
    search() {
      this.currentPage = 1
      this.getUserPage()
    },
    handleAdd() {
      this.user = Object.assign({}, defaultUser)
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.user = deepClone(row)
      this.dialogVisible = true
    },
    handelDel(row) {

    },
    handleSizeChange(size) {
      this.query.pageSize = size
    },
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage
    },
    handleDelete(row) {
      this.$confirm('确认删除用户?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteUser(row.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getUserPage()
        // refreshArr(this.userList, user => user.iID === this.user.iID, this.user)
      }).catch(err => console.error(err))
    },
    submit() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          const isEdit = !!this.user.id
          if (isEdit) {
            await sysInvoiceHeaderUpdate(this.user)
            this.$message.success('编辑成功')
            this.getUserPage()
          } else {
            await sysInvoiceHeaderAdd(this.user)
            this.$message.success('新增成功')
            this.getUserPage()
          }
          this.dialogVisible = false
        }
      })
    }
  }
}
</script>
